<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_aixiaoyi/model')->方法名();
*/
namespace jy_aixiaoyi;
defined('BY_JYA') or exit('error');
class wenxin extends \plugin{
	//发起http请求
	public function request($rurl,$post=null,$isres=false){
		$basic=$this->plugin_setting('basic');
		if(!$basic['apikey2']){
			if($isres){
				$res['choices'][0]['text']='chatAI暂时无法使用，请联系管理员，设置好基本参数文心API Key';
				return $res;
			}else{
				exi('chatAI暂时无法使用，请联系管理员，设置好基本参数API Key','error');
			}
		}
		if(!$basic['secretkey2']){
			if($isres){
				$res['choices'][0]['text']='chatAI暂时无法使用，请联系管理员，设置好基本参数文心Secret Key';
				return $res;
			}else{
				exi('chatAI暂时无法使用，请联系管理员，设置好基本参数文心Secret Key','error');
			}
		}
		$access_token=$this->access_token($basic);
		$rurl .='?access_token='.$access_token;
		$post=ijson_encode($post);
		$result=cfc('http')->ihttp_request($rurl,$post);
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if($data['errcode']){
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			$message='访问接口错误，以下为原始数据：'.$result['content'];
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	public function access_token($basic=array()){
		$basic=$basic?:$this->plugin_setting('basic');
		if($basic['expires_in']>time() && $basic['access_token']){
			return $basic['access_token'];
		}
		if(!$basic['apikey2']){
			if($isres){
				$res['choices'][0]['text']='chatAI暂时无法使用，请联系管理员，设置好基本参数文心API Key';
				return $res;
			}else{
				exi('chatAI暂时无法使用，请联系管理员，设置好基本参数API Key','error');
			}
		}
		if(!$basic['secretkey2']){
			if($isres){
				$res['choices'][0]['text']='chatAI暂时无法使用，请联系管理员，设置好基本参数文心Secret Key';
				return $res;
			}else{
				exi('chatAI暂时无法使用，请联系管理员，设置好基本参数文心Secret Key','error');
			}
		}
		$url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='.$basic['apikey2'].'&client_secret='.$basic['secretkey2'];
		$result=cfc('http')->ihttp_request($url);
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$res=@json_decode($data,true);
		if(!$res['access_token']){
			exi('获取access_token失败！'.$res['error'].'-'.$res['error_description'],'error');
		}
		$basic['refresh_token']=$res['refresh_token'];
		$basic['expires_in']=$res['expires_in']+time();
		$basic['access_token']=$res['access_token'];
		$this->plugin_setting('basic',$basic);
		return $basic['access_token'];
	}
	//获取聊天文本
	public function getmsg($content,$isexi=false) {
		$basic=$this->plugin_setting('basic');
		if($basic['isku']){
			$msg=$this->getwenda($content);
			if($msg){
				return $msg;
			}
		}
		if(strpos($basic['apis'],'2') !== false){
			
		}else{
			return false;
		}
	
		//return '这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！';
		//text-davinci-003 gpt-3.5-turbo
		$url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
		/*$post=array(
			'model'=>'text-davinci-003',
			'prompt'=>$content,
			'max_tokens'=>2048,
		);*/
		$messages[]=array('role'=>'user','content'=>$content);
		$post=array(
			'messages'=>$messages,
		);
		$isres=$isexi?false:true;
		$res=$this->request($url,$post,$isres);
		//print_r($res);exit;
		if($res['error_code']){
			$res['message']=$res['error_msg']?:$res['error']['message'];
			if($isexi){
				exi('获取失败：'.$res['error_code'].','.$res['message'],'error');
			}else{
				return $basic['nomsg']?:'chatAI暂时无法回答您的问题！请联系管理员！';
			}
		}
		//$msg=$res['choices'][0]['text'];
		$msg=$res['result'];
		if($msg){
			$this->upwenda($content,$msg);
		}
		return $msg;
	}
	public function yufee() {
		$basic=$this->plugin_setting('basic');
		if(!$basic['apikey2']){
			return false;
		}
		$url = "https://api.openai.com/v1/chat/completions";
		$messages[]=array('role'=>'user','content'=>$content);
		$post=array(
			'model'=>'gpt-3.5-turbo',
			'messages'=>$messages,
			'temperature'=>0.7,
		);
		$res=$this->request($url,$post,true);
		if($res['error']){
			$res['message']=$res['message']?:$res['error']['message'];
			if($isexi){
				exi('获取失败：'.$res['type'].','.$res['message'],'error');
			}else{
				return '获取余额失败：'.$res['message'];
			}
		}
		$msg=$res['choices'][0]['message']['content'];
		return $msg;
	}
	public function getwenda($msg=''){
		$wenda=pdo_get('jy_aixiaoyi_wenda',array('title like'=>'%'.trim($msg).'%','status'=>1,'uniacid'=>$_SESSION['uniacid']),'','paixu desc,id desc');
		return $wenda['msg'];
	}
	//机器人入库
	public function upwenda($title='',$msg=''){
		$wenda=pdo_get('jy_aixiaoyi_wenda',array('title'=>trim($title),'uniacid'=>$_SESSION['uniacid']));
		if($wenda['id'] || !$title || !$msg){
			return false;
		}
		$data=array(
			'uniacid'=>$_SESSION['uniacid'],
			'title'=>$title,
			'msg'=>$msg,
			'status'=>1,
			'createtime'=>TIMESTAMP
		);
		pdo_insert('jy_aixiaoyi_wenda',$data);
		return true;
	}
}
?>